<template>
	<view class="roc-diyform">
		<u-form class="roc-form" :model="form" :rules="rules" ref="uForm" errorType="message" labelPosition="top"
			labelWidth="auto" :labelStyle="{ fontSize: '30rpx', lineHeight: '1.6' }">
			<block v-for="(item, index) in formRuleJson" :key="index">
				<!-- 字符 -->
				<u-form-item :prop="item.field" :label="item.title" :key="index" :borderBottom="true"
					v-if="item.type == 'input'">
					<u-input v-model="form[item.field]" :type="item.props.type || 'text'"
						:disabled="item.props.disabled || false" :clearable="item.props.clearable || false"
						:maxlength="item.props.maxlength || 140" :placeholder="item.props.placeholder || '请填写'"
						:showWordLimit="item.props.showWordLimit || false" :focus="item.props.autofocus || false"
						:readonly="item.props.readonly || false" :prefixIcon="item.props.prefixIcon || ''"
						:prefixIconStyle="{ fontSize: '26rpx' }" :suffixIcon="item.props.suffixIcon || ''"
						:suffixIconStyle="{ fontSize: '26rpx' }" border="none">
						<template #suffix>
							<text class="input-right-slot"
								v-if="item.type == 'input'">{{ item.children[0].children[0] }}</text>
						</template>
					</u-input>
				</u-form-item>
				<!-- 计数器 -->
				<u-form-item :prop="item.field" :label="item.title" :key="index" :borderBottom="true"
					v-if="item.type == 'inputNumber'">
					<u-number-box v-model="form[item.field]" button-size="60rpx" inputWidth="200rpx"
						iconStyle="color: #333;font-size: 26rpx" :min="item.props.min || 0"
						:max="item.props.max || Number.MAX_SAFE_INTEGER" :step="item.props.step || 1"
						:disabled="item.props.disabled || false"
						:showMinus="item.props.controls == undefined ? true : item.props.controls"
						:showPlus="item.props.controls == undefined ? true : item.props.controls"></u-number-box>
				</u-form-item>
				<!-- 开关 -->
				<u-form-item :prop="item.field" :label="item.title" :key="index" :borderBottom="true"
					v-if="item.type == 'switch'">
					<u-switch v-model="form[item.field]" size="46" :disabled="item.props.disabled"
						:activeValue="item.props.activeValue || true"
						:inactiveValue="item.props.inactiveValue || false"></u-switch>
				</u-form-item>
				<!-- 日期选择器 -->
				<u-form-item :prop="item.field" :label="item.title" :key="index" :borderBottom="true"
					v-if="item.type == 'datePicker'">
					<roc-date-picker :item="item" v-model="form[item.field]"></roc-date-picker>
				</u-form-item>
				<!-- 滑块 -->
				<u-form-item :prop="item.field" :label="item.title" :key="index" :borderBottom="true"
					v-if="item.type == 'slider'">
					<u-slider v-model="form[item.field]" :min="item.props.min || 1" :max="item.props.max || 100"
						:step="item.props.step || 1" :showValue="item.props.showInput || false"></u-slider>
				</u-form-item>
				<!-- 评分 -->
				<u-form-item :prop="item.field" :label="item.title" :key="index" :borderBottom="true"
					v-if="item.type == 'rate'">
					<u-rate size="36rpx" v-model="form[item.field]" :disabled="item.props.disabled || false"
						:count="item.props.max || 5" :allowHalf="item.props.allowHalf || false"
						:inactiveColor="item.props.voidColor || '#b2b2b2'" :minCount="0"></u-rate>
				</u-form-item>
				<!-- 富文本 -->
				<u-form-item :prop="item.field" :label="item.title" :key="index" :borderBottom="true"
					v-if="item.type == 'fc-editor'">
					<roc-editor v-model="form[item.field]" :html="form[item.field]"
						:readOnly="item.props.disabled || false"></roc-editor>
				</u-form-item>
				<!-- 选择器 -->
				<u-form-item @click="curClickFormItem(item)" :prop="item.field" :label="item.title" :key="index"
					:borderBottom="true" v-if="item.type == 'select' && !item.props.multiple">
					<roc-select :formData="form" :item="item" v-model="form[item.field]"></roc-select>
				</u-form-item>
				<!-- 选择器-多选 -->
				<u-form-item @click="curClickFormItem(item)" :prop="item.field" :label="item.title" :key="index"
					:borderBottom="true" v-if="item.type == 'select' && item.props.multiple">
					<roc-select-multiple :item="item" v-model="form[item.field]"></roc-select-multiple>
				</u-form-item>
				<!-- 级联选择器 -->
				<u-form-item @click="curClickFormItem(item)" :prop="item.field" :label="item.title" :key="index"
					:borderBottom="true" v-if="item.type == 'cascader'">
					<roc-cascader :formData="form" :item="item" v-model="form[item.field]"></roc-cascader>
				</u-form-item>
				<!-- 单选框 -->
				<u-form-item :prop="item.field" :label="item.title" :key="index" :borderBottom="true"
					v-if="item.type == 'radio'">
					<roc-radio :item="item" v-model="form[item.field]"></roc-radio>
				</u-form-item>
				<!-- 多选框 -->
				<u-form-item :prop="item.field" :label="item.title" :key="index" :borderBottom="true"
					v-if="item.type == 'checkbox'">
					<roc-checkbox :item="item" v-model="form[item.field]"></roc-checkbox>
				</u-form-item>
				<!-- 文件 & 图片上传 -->
				<u-form-item :prop="item.field" :label="item.title" :key="index" :borderBottom="true"
					v-if="item.type == 'upload'">
					<roc-upload-file v-if="item.props.uploadType == 'file'" :item="item" v-model="form[item.field]"
						:showValue="form[item.field]"></roc-upload-file>
					<roc-upload-image v-else :item="item" v-model="form[item.field]"></roc-upload-image>
				</u-form-item>
			</block>
		</u-form>
		<view class="u-p-30" v-if="showSubmitBtn && showForm && formRuleJson.length">
			<u-button type="primary" hover-class="none" :custom-style="{ backgroundColor: '#409eff', color: '#fff' }"
				shape="circle" @click="submit">
				提交
			</u-button>
		</view>
		<!-- <u-empty v-else mode="data" textSize="30" iconSize="120" marginTop="160" /> -->
		<view style="text-align: center;padding-top: 100rpx;" v-if="!showForm && !formRuleJson.length">
			<image src="@/static/img/nullData.png" style="width: 160px;height: 160px;"></image>
			<view style="color: #888;">暂无数据~</view>
		</view>
	</view>
</template>

<script>
	import watchformDatahx from './mixins/watchformDatahx.js';
	import {
		getModelFieldList
	} from '@/api/model.js';

	import RocDatePicker from './components/roc-date-picker/roc-date-picker.vue';
	import RocEditor from './components/roc-editor/roc-editor.vue';
	import RocSelect from './components/roc-select/roc-select.vue';
	import RocSelectMultiple from './components/roc-select-multiple/roc-select-multiple.vue';
	import RocCascader from './components/roc-cascader/roc-cascader.vue';
	import RocRadio from './components/roc-radio/roc-radio.vue';
	import RocCheckbox from './components/roc-checkbox/roc-checkbox.vue';
	import RocUploadImage from './components/roc-upload-image/roc-upload-image.vue';
	import RocUploadFile from './components/roc-upload-file/roc-upload-file.vue';
	export default {
		name: 'roc-diyform',
		mixins: [watchformDatahx],
		components: {
			RocEditor,
			RocDatePicker,
			RocSelect,
			RocSelectMultiple,
			RocCascader,
			RocRadio,
			RocCheckbox,
			RocUploadImage,
			RocUploadFile
		},
		props: {
			// 模型id
			modelId: {
				type: [String, Number],
				default: ''
			},
			// 编辑回显的数据
			showFormData: {
				type: Object,
				default () {
					return {};
				}
			},
			// 按钮隐藏（隐藏按钮后需在父组件手动触发 submit 方法）
			showSubmitBtn: {
				type: Boolean,
				default: true
			}
		},
		data() {
			return {
				// 表单相关
				showForm: false,
				form: {},
				rules: {},
				formRuleJson: [],
				// 当前点击的字段
				curChangeField: ''
			};
		},
		created() {
			this.reqDiyFormJson();
		},
		methods: {
			// 当前点击的表单项
			curClickFormItem(item) {
				this.curChangeField = item.field;
			},
			// 请求表单json信息
			reqDiyFormJson() {
				if (!this.modelId) return;
				getModelFieldList({
					model_id: this.modelId
				}).then(({
					data: {
						data
					}
				}) => {
					if (data != null) {
						const newData = data
							.map(fieldObj => {
								fieldObj.attr_json = JSON.parse(fieldObj.attr_json);
								// 判断是否有props，没有则加上（防止使用数据item.props.xxx报错）
								if (!fieldObj.attr_json.hasOwnProperty('props')) {
									fieldObj.attr_json.props = {};
								}
								// 级联选择器 判断是否有props.props，没有则加上（防止使用数据item.props.props.xxx报错）
								if (fieldObj.attr_json.type == 'cascader') {
									if (!fieldObj.attr_json.props.hasOwnProperty('props')) {
										fieldObj.attr_json.props.props = {};
									}
								}
								return fieldObj;
							})
							.reverse();

						const addShowData = newData.filter(fieldObj => {
							return fieldObj.add_hide == '0';
						});
						const editShowData = newData.filter(fieldObj => {
							return fieldObj.edit_hide == '0';
						});
						this.$watch('showFormData', {
							handler(showFormData) {
								const keyArray = Object.keys(showFormData);
								if (keyArray.length) {
									// 编辑
									this.formRuleJson = editShowData.map(item => item.attr_json);
								} else {
									// 添加
									this.formRuleJson = addShowData.map(item => item.attr_json);
								}
								console.log("formRuleJson===============>", this.formRuleJson)
								this.checkForm(this.formRuleJson);
							},
							immediate: true
						});
					}
				});
			},
			// 设置表单验证规则
			checkForm(formRuleJson) {
				formRuleJson.forEach(item => {
					this.$set(this.rules, item.field, item.validate);
					// 不同组件默认值
					if (item.type == 'inputNumber') {
						this.$set(this.form, item.field, item.props.min || 0);
					} else if (item.type == 'switch') {
						this.$set(this.form, item.field, item.props.inactiveValue || false);
					} else if (item.type == 'slider') {
						this.$set(this.form, item.field, item.props.min || 0);
					} else if (item.type == 'rate') {
						this.$set(this.form, item.field, 0);
					} else if (item.type == 'cascader') {
						this.$set(this.form, item.field, []);
					} else if (item.type == 'checkbox') {
						this.$set(this.form, item.field, []);
					} else if (item.type == 'upload') {
						this.$set(this.form, item.field, []);
					} else if (item.type == 'input' || item.type == 'select') {
						this.$set(this.form, item.field, item.value);
					} else {
						this.$set(this.form, item.field, '');
					}
				});
				console.log("newForm========>", this.form)
				this.showForm = true;
				this.$nextTick(() => {
					this.$refs.uForm.setRules(this.rules);
				});
				// 回显数据
				this.$nextTick(() => {
					this.handleShowformData();
				});
			},
			// 表单数据回显
			handleShowformData() {
				if (!Object.keys(this.showFormData).length) return;
				// 回显数据转换
				const newRow = JSON.parse(JSON.stringify(this.showFormData));
				this.formRuleJson.forEach(item => {
					// 选择器 单选数据处理（多选为数组）
					if (item._fc_drag_tag == 'radio') {
						// 是否是字符串数字
						if (!isNaN(parseInt(newRow[item.field]))) {
							newRow[item.field] = parseInt(newRow[item.field]);
						}
					} else if (item._fc_drag_tag == 'select' && (!item.props || !item.props.multiple)) {
						// 是否是字符串数字
						if (!isNaN(parseInt(newRow[item.field]))) {
							newRow[item.field] = parseInt(newRow[item.field]);
						}
					} else {
						if (item._fc_drag_tag == 'cascader' || item._fc_drag_tag == 'checkbox') {
							if (newRow[item.field] != '') {
								newRow[item.field] = newRow[item.field] && newRow[item.field].split(',');
								newRow[item.field] = newRow[item.field].map(item => {
									// 是否是字符串数字
									if (isNaN(parseInt(item))) {
										return item;
									} else {
										return parseInt(item);
									}
								});
							} else {
								newRow[item.field] = [];
							}
						}
						if (item._fc_drag_tag == 'upload') {
							// 回显如果是上传组件
							const urlList = newRow[item.field] == undefined ? '' : newRow[item.field];
							let urlArray = [];
							if (urlList.length) {
								urlArray = urlList.split(',');
							}
							delete newRow[item.field];
						}
					}
				});
				this.form = JSON.parse(JSON.stringify(newRow));
				console.log("表单回显数据", newRow)

			},
			async submit() {
				console.log(this.form)
				this.formRuleJson.forEach(item => {
					if (item.type == "select" && item.props.multiple) {
						if (typeof this.form[item.field] != "object") {
							this.form[item.field] = String(this.form[item.field]).split(",")
						}

					}
				})
				await this.$refs.uForm.validate();

				// 提交数据需要将 数组 转换为 逗号分割
				const formData = JSON.parse(JSON.stringify(this.form));
				for (let key in formData) {
					if (uni.$u.test.array(formData[key])) {
						formData[key] = formData[key].join(',');
					}
				}
				this.$emit('roc-submit', formData);
			}
		}
	};
</script>

<style lang="scss">
	.input-right-slot {
		color: #303133;
		font-size: 26rpx;
	}

	.u-slider {
		width: 100%;
	}

	.u-form-item {
		margin-bottom: 16rpx;
	}
</style>
